package com.gable.report.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gable.report.common.util.HttpHelper;
import com.gable.report.common.util.ReturnResultUtil;
import com.gable.report.model.Dispatching;
import com.gable.report.model.UpkeepInfo;
import com.gable.report.model.User;
import com.gable.report.util.FileUploadUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.gable.report.util.HttpProcessUtil.getAccessPath;
import static com.gable.report.util.HttpProcessUtil.headerList;

/**
 * @Author: 杨青桦
 * @Description:  医院操作
 * @Date: 2018/3/21 14:30
 */
@Controller
public class ChartsForHospitalOperationController {

    private final Log logger = LogFactory.getLog(this.getClass());

    private static final String rootPath = "charts/operation/";

    @Autowired
    HttpServletRequest request;

    @Value("${hospital.address}")
    String hospitalAddress;

    /**
     * @Author: 杨青桦
     * @Description: 保养评价操作
     * @Date: 2018/3/21 16:24
     * @param dispatchId
     * @param upkeepId
     * @param dispatching
     * @param upkeepInfo
     * @return
     */
    @RequestMapping(value="upkeep/confirmUpkeep",method= RequestMethod.POST,produces = "application/json; charset=utf-8")
    @ResponseBody
    public ReturnResultUtil confirmUpkeep(@RequestParam String dispatchId,@RequestParam  String upkeepId, Dispatching dispatching,
                                          UpkeepInfo upkeepInfo,HttpServletRequest request) {
       String result;
        try {
            User user = (User) request.getSession().getAttribute("loginUser");
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("dispatchId", dispatchId);
            paramMap.put("upkeepId", upkeepId);
            paramMap.put("dispatching",JSONObject.toJSONString(dispatching));
            paramMap.put("upkeepInfo",JSONObject.toJSONString(upkeepInfo));
            paramMap.put("user", JSONObject.toJSONString(user));
            String path = rootPath + "upkeep/confirmUpkeep";    //接口路径
            String url = getAccessPath(hospitalAddress,path); //访问完整路径
            result = HttpHelper.postRequestResponseBodyAsString(headerList,url, paramMap);
            if(StringUtils.isEmpty(result)){
                return new ReturnResultUtil(0, "网络异常",result);
            }
            logger.info("-----保养------:保养id为" + upkeepId + "，派工id为" + dispatchId + "评价成功;");
            logger.info("操作人：" + user.getId());
            return JSON.parseObject(result,ReturnResultUtil.class);
        } catch (Exception e){
            e.printStackTrace();
            return new ReturnResultUtil(0,"操作异常");
        }
    }


    /**
     * @Author: 杨青桦
     * @Description:  维修确认时获取维修费用
     * @Date: 2018/3/23 11:12
     * @param dispatchId
     * @return
     */
    @RequestMapping(value="dispatching/getCost",method= RequestMethod.POST,produces = "application/json; charset=utf-8")
    @ResponseBody
    public ReturnResultUtil dispatchingGetCost(@RequestParam String dispatchId) {
        String result;
        try {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("dispatchId", dispatchId);
            String path = rootPath + "dispatching/getCost";    //接口路径
            String url = getAccessPath(hospitalAddress, path); //访问完整路径
            result = HttpHelper.postRequestResponseBodyAsString(headerList, url, paramMap);
            if(StringUtils.isEmpty(result)){
                return new ReturnResultUtil(0, "网络异常",result);
            }
            return JSON.parseObject(result,ReturnResultUtil.class);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnResultUtil(0, "查询异常");
        }
    }


    /**
     * @Author: 杨青桦
     * @Description:  维修评价
     * @Date: 2018/3/23 11:38
     * @param dispatchId
     * @return
     */
    @RequestMapping(value="maintenance/update",method= RequestMethod.POST,produces = "application/json; charset=utf-8")
    @ResponseBody
    public ReturnResultUtil maintenanceUpdate(
            String repairId,						// 报修ID
            String dispatchId,						// 派工ID
            String repairStatus,					// 维修状态（已修复或者未修复）
            String hospitalReceivedDate,			// 医院确认收到设备时间
            String score,							// 总体评分
            String speedScore,						// 服务器响应速度评分
            String qualityScore,					// 服务质量评分
            String attitudeScore,					// 服务态度评分
            String comment,						    // 其它反馈
            String repairCondition,					// 维修状况
            String artificialCost,					// 人工费用
            String partCost,						// 备件费用
            String otherCost,						// 其它费用
            String expressCost,						// 快递费用
            String sumCost,							// 总费用
            String remark							// 备注
                                              ) {
        String result;
        try {
            Map<String, String> paramMap = new HashMap<>();
            User user = (User) request.getSession().getAttribute("loginUser");
            paramMap.put("userId",user.getId()+"");
            paramMap.put("repairId", repairId);
            paramMap.put("dispatchId", dispatchId);
            paramMap.put("repairStatus",repairStatus);
            paramMap.put("hospitalReceivedDate",hospitalReceivedDate);
            paramMap.put("score",score);
            paramMap.put("speedScore",speedScore);
            paramMap.put("qualityScore",qualityScore);
            paramMap.put("attitudeScore",attitudeScore);
            paramMap.put("comment",comment);
            paramMap.put("repairCondition",repairCondition);
            paramMap.put("artificialCost",artificialCost);
            paramMap.put("partCost",partCost);
            paramMap.put("otherCost",otherCost);
            paramMap.put("expressCost",expressCost);
            paramMap.put("sumCost",sumCost);
            paramMap.put("remark",remark);
            String path = rootPath + "maintenance/update";    //接口路径
            String url = getAccessPath(hospitalAddress, path); //访问完整路径
            result = HttpHelper.postRequestResponseBodyAsString(headerList, url, paramMap);
            if(StringUtils.isEmpty(result)){
                return new ReturnResultUtil(0, "网络异常",result);
            }
            ReturnResultUtil rru = JSON.parseObject(result,ReturnResultUtil.class);
            if(rru.getRet() == 1){
                logger.info("-----维修确认-------:维修id为" + repairId + "，派工id为" + dispatchId);
                logger.info("操作人：" + user.getId());
            }
            return rru;
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnResultUtil(0, "查询异常");
        }
    }


    /**
     * @Author: 杨青桦
     * @Description: 查询本医院的工程师(自修)
     * @Date: 2018/3/23 15:12
     * @return
     * @throws IOException
     */
    @RequestMapping(value="repair/queryUserNameId",method=RequestMethod.GET,produces="application/json;charset=utf-8")
    @ResponseBody
    public String queryUserNameId(){
        String result;
        try {
            Map<String, String> paramMap = new HashMap<>();
            User user = (User) request.getSession().getAttribute("loginUser");
            paramMap.put("user", JSONObject.toJSONString(user));
            String path = rootPath + "repair/queryUserNameId";    //接口路径
            String url = getAccessPath(hospitalAddress, path); //访问完整路径
            result = HttpHelper.postRequestResponseBodyAsString(headerList, url, paramMap);
            if(StringUtils.isEmpty(result)){
                return JSON.toJSONString(new ReturnResultUtil(0, "网络异常",result));
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(new ReturnResultUtil(0, "查询异常"));
        }
    }

    /**
     * @Author: 杨青桦
     * @Description:  查询该医院所有维修商(报表和医院项目接口内容不同)
     * @Date: 2018/3/23 15:33
     */
    @RequestMapping(value = "serviceProvider/queryServiceProviderHospitalList", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil queryServiceProviderList(String deviceId) {
        String result;
        try {
            User user = (User) request.getSession().getAttribute("loginUser");
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("deviceId", deviceId);
            paramMap.put("user", JSONObject.toJSONString(user));
            String path = rootPath + "serviceProvider/queryServiceProviderHospitalList";    //接口路径
            String url = getAccessPath(hospitalAddress,path); //访问完整路径
            result = HttpHelper.postRequestResponseBodyAsString(headerList,url, paramMap);
            if(StringUtils.isEmpty(result)){
                return new ReturnResultUtil(0, "网络异常",result);
            }
            return JSON.parseObject(result,ReturnResultUtil.class);
        } catch (Exception e){
            e.printStackTrace();
            return new ReturnResultUtil(500,"操作异常");
        }
    }

    /**
     * @Author: 杨青桦
     * @Description: 查询维修商工程师列表
     * @Date: 2018/3/23 15:17
     */
    @RequestMapping(value="repair/queryUserIdNameList",method=RequestMethod.POST,produces="application/json;charset=utf-8")
    @ResponseBody
    public String queryRepairUserIdNameList(String serviceProviderId){
        String result;
        try {
            Map<String, String> paramMap = new HashMap<>();
            User user = (User) request.getSession().getAttribute("loginUser");
            paramMap.put("user", JSONObject.toJSONString(user));
            paramMap.put("serviceProviderId",serviceProviderId);    //维修商id
            String path = rootPath + "repair/queryUserIdNameList";    //接口路径
            String url = getAccessPath(hospitalAddress, path); //访问完整路径
            result = HttpHelper.postRequestResponseBodyAsString(headerList, url, paramMap);
            if(StringUtils.isEmpty(result)){
                return JSON.toJSONString(new ReturnResultUtil(0, "网络异常",result));
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(new ReturnResultUtil(0, "查询异常"));
        }
    }

    /**
     * @Author: 杨青桦
     * @Description: 判断不能一个报修在院方未确认的情况下不能指派同一个维修商
     * @Date: 2018/3/23 16:59
     */
    @RequestMapping(value="repair/checkServiceProvider", method=RequestMethod.POST,produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil checkRepairServiceProvider(String id,String serviceProviderId){
        String result;
        try {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("id",id);
            paramMap.put("serviceProviderId",serviceProviderId);
            String path = rootPath + "repair/checkServiceProvider";    //接口路径
            String url = getAccessPath(hospitalAddress,path); //访问完整路径
            result = HttpHelper.postRequestResponseBodyAsString(headerList,url, paramMap);
            if(StringUtils.isEmpty(result)){
                new ReturnResultUtil(0, "网络异常",result);
            }
            return JSON.parseObject(result,ReturnResultUtil.class);
        } catch (Exception e){
            e.printStackTrace();
            return new ReturnResultUtil(0,"操作异常");
        }
    }

    /**
     * @Author: 杨青桦
     * @Description:  查询维修详情信息（用于model展示）
     * @Date: 2018/3/23 17:18
     */
    @RequestMapping(value="repair/queryRepairView",method=RequestMethod.POST,produces="application/json;charset=utf-8")
    public @ResponseBody String queryRepairView(String id) {
        String result;
        try {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("id",id);    //设备id
            String path = rootPath + "repair/queryRepairView";    //接口路径
            String url = getAccessPath(hospitalAddress, path); //访问完整路径
            result = HttpHelper.postRequestResponseBodyAsString(headerList, url, paramMap);
            if(StringUtils.isEmpty(result)){
                return JSON.toJSONString(new ReturnResultUtil(0, "网络异常",result));
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(new ReturnResultUtil(0, "查询异常"));
        }
    }


    /**
     * @Author: 杨青桦
     * @Description:  查询设备报修处理时需要的合同信息
     * @Date: 2018/3/23 17:22
     */
    @RequestMapping(value="/contract/getContractInfo",method=RequestMethod.POST,produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil getContractInfo(String assetsId) {
        String result;
        try {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("assetsId",assetsId);    //设备id
            String path = rootPath + "contract/getContractInfo";    //接口路径
            String url = getAccessPath(hospitalAddress,path); //访问完整路径
            result = HttpHelper.postRequestResponseBodyAsString(headerList,url, paramMap);
            if(StringUtils.isEmpty(result)){
                return new ReturnResultUtil(0, "网络异常",result);
            }
            return JSON.parseObject(result,ReturnResultUtil.class);
        } catch (Exception e){
            e.printStackTrace();
            return new ReturnResultUtil(0,"查询异常");
        }
    }


    /**
     * @Author: 杨青桦
     * @Description: 查询设备的历史维修记录
     * @Date: 2018/3/26 10:57
     * @param assetsId
     * @return
     */
    @RequestMapping(value="/repair/queryRepairAssets",method=RequestMethod.POST,produces="application/json;charset=utf-8")
    @ResponseBody
    public String queryRepairAssets(String assetsId){
        String result;
        try {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("assetsId",assetsId);    //设备id
            String path = rootPath + "repair/queryRepairAssets";    //接口路径
            String url = getAccessPath(hospitalAddress, path); //访问完整路径
            result = HttpHelper.postRequestResponseBodyAsString(headerList, url, paramMap);
            if(StringUtils.isEmpty(result)){
                return JSON.toJSONString(new ReturnResultUtil(0, "网络异常",result));
            }
            if("[]".equals(result)){
                return JSON.toJSONString(new ReturnResultUtil(1, "查询成功",""));
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(new ReturnResultUtil(0, "查询异常"));
        }
    }

    /**
     * @Author: 杨青桦
     * @Description: 报修指派处理
     * @Date: 2018/3/26 14:54
     * @param request
     * @param id
     * @param serviceProviderId
     * @param engineer
     * @param otherEngineer
     * @param engineerId
     * @param remark
     * @param repairType
     * @param maintenanceType
     * @param hospitalSendDate
     * @param hospitalSendNumber
     * @param assignTime
     * @return
     */
    @RequestMapping(value="repair/addDispatchInfo",method=RequestMethod.POST,produces="application/json;charset=utf-8")
    public @ResponseBody String addDispatchInfo(HttpServletRequest request,
                                                String id,
                                                String serviceProviderId,
                                                String engineer,
                                                String otherEngineer,
                                                String engineerId,
                                                String remark,
                                                String repairType,
                                                String maintenanceType,
                                                String hospitalSendDate,
                                                String hospitalSendNumber,
                                                String assignTime) {
        User user = (User) request.getSession().getAttribute("loginUser");
        Map<String,Object> resultMap = new HashMap<>();
        // 快递单上传
        String key = "";
        String photos = "";
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> files = multipartRequest.getFiles("files");
            if(files != null && files.size()>0){
                for(MultipartFile m : files){
                    if(m.getBytes().length != 0){
                        String suffix = m.getOriginalFilename()
                                .substring(m.getOriginalFilename().lastIndexOf(".")+1);
                        key = "express/" + new Date().getTime()+"."+suffix;
                        boolean bl = FileUploadUtil.fileUpload(m.getBytes(), key,m.getSize());

                        if (!bl) {
                            resultMap.put("ret",0);
                            resultMap.put("msg","文件上传失败");
                        }
                        photos += FileUploadUtil.REALMNAME+"/"+key+",";
                    }
                }
                logger.info("---------报表维修指派文件上传成功，文件名为：" + photos);
            }else{
                resultMap.put("ret",1);
                resultMap.put("msg","无文件上传");
            }
        } catch (IOException e) {
            e.printStackTrace();
            resultMap.put("ret",0);
            resultMap.put("msg","文件上传失败");
        }
        //文件上传失败,直接返回失败信息
        if(resultMap.get("ret") != null &&(Integer)resultMap.get("ret") == 0){
            return JSON.toJSONString(resultMap);
        }
        String result;
        try {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("user",JSON.toJSONString(user));
            paramMap.put("rid", id);									// 维修id
            paramMap.put("serviceProviderId", serviceProviderId);		// 维修商ID
            paramMap.put("engineer", engineer);							// 工程师名字
            paramMap.put("otherEngineer", otherEngineer);				// 其他工程师
            paramMap.put("engineerId", engineerId);						// 工程师ID
            paramMap.put("remark", remark);								// 备注
            paramMap.put("repairType", repairType); 					// 维修类型(5001:自己修、5002:维修商修、5003:其他维修)
            paramMap.put("maintenanceType",maintenanceType);			// 维修方式（无<0>、送修<1>）
            paramMap.put("hospitalSendDate",hospitalSendDate);			// 医院送出时间
            paramMap.put("hospitalSendNumber",hospitalSendNumber);		// 医院送出时的快递单号
            paramMap.put("assignTime",assignTime);						// 派工时间
            paramMap.put("photos",photos);                              // 上传文件名称
            String path = rootPath + "repair/addDispatchInfo";          //接口路径
            String url = getAccessPath(hospitalAddress, path);          //访问完整路径
            result = HttpHelper.postRequestResponseBodyAsString(headerList, url, paramMap);
            if(StringUtils.isEmpty(result)){
                return JSON.toJSONString(new ReturnResultUtil(0, "网络异常",result));
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(new ReturnResultUtil(0, "操作异常"));
        }
    }

    /** 
     * @Author: 杨青桦
     * @Description:  维修评价参考信息
     * @Date: 2018/4/12 20:24
     */
    @RequestMapping(value="/repair/evaluate",method=RequestMethod.POST,produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil queryRepairInfoForEvaluate(String repairId) {
        String result;
        try {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("repairId",repairId);    //设备id
            String path = rootPath + "/repair/evaluate";    //接口路径
            String url = getAccessPath(hospitalAddress,path); //访问完整路径
            result = HttpHelper.postRequestResponseBodyAsString(headerList,url, paramMap);
            if(StringUtils.isEmpty(result)){
                return new ReturnResultUtil(0, "网络异常",result);
            }
            return JSON.parseObject(result,ReturnResultUtil.class);
        } catch (Exception e){
            e.printStackTrace();
            return new ReturnResultUtil(0,"查询异常");
        }
    }
}
